package leetcode;

public class Pro0106 {

    public static void main(String[] args) {
        System.out.println(compressString("aabcccccaa"));
    }

    public static String compressString(String S) {
        int length = S.length();
        StringBuilder sb = new StringBuilder();
        int count = 1;
        for (int l = 0; l < length; ) {
            for (int r = l + 1; r < length; r++) {
                if (r == length - 1) {
                    sb.append(S.charAt(l));
                    sb.append(count + 1);
                    return sb.toString().length() > length ? S : sb.toString();
                } else if (S.charAt(l) == S.charAt(r)) {
                    count++;
                } else {
                    sb.append(S.charAt(l));
                    sb.append(count);
                    l = r;
                    count = 1;
                }
            }
        }
        return sb.toString().length() > length ? S : sb.toString();
    }
}
